// 简化的配置管理

use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use log::info;
use super::ServiceError;

// 配置结构
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SimpleConfig {
    pub service_name: String,
    pub version: String,
    pub max_memory: usize,
    pub max_processes: usize,
    pub max_files: usize,
    pub debug_mode: bool,
    pub settings: HashMap<String, String>,
}

impl Default for SimpleConfig {
    fn default() -> Self {
        Self {
            service_name: "quick-simple-service".to_string(),
            version: "1.0.0".to_string(),
            max_memory: 1024 * 1024 * 1024, // 1GB
            max_processes: 256,
            max_files: 1024,
            debug_mode: true,
            settings: HashMap::new(),
        }
    }
}

impl SimpleConfig {
    pub fn new() -> Self {
        info!("Creating new SimpleConfig with default values");
        Self::default()
    }
    
    pub fn with_name(mut self, name: &str) -> Self {
        self.service_name = name.to_string();
        self
    }
    
    pub fn with_memory_limit(mut self, memory_mb: usize) -> Self {
        self.max_memory = memory_mb * 1024 * 1024;
        self
    }
    
    pub fn set_setting(&mut self, key: &str, value: &str) {
        self.settings.insert(key.to_string(), value.to_string());
    }
    
    pub fn get_setting(&self, key: &str) -> Option<&str> {
        self.settings.get(key).map(|s| s.as_str())
    }
    
    pub fn validate(&self) -> Result<(), ServiceError> {
        if self.max_memory == 0 {
            return Err(ServiceError::ConfigurationError("Max memory cannot be zero".to_string()));
        }
        
        if self.max_processes == 0 {
            return Err(ServiceError::ConfigurationError("Max processes cannot be zero".to_string()));
        }
        
        if self.max_files == 0 {
            return Err(ServiceError::ConfigurationError("Max files cannot be zero".to_string()));
        }
        
        if self.service_name.is_empty() {
            return Err(ServiceError::ConfigurationError("Service name cannot be empty".to_string()));
        }
        
        Ok(())
    }
    
    pub fn to_json(&self) -> Result<String, ServiceError> {
        serde_json::to_string_pretty(self)
            .map_err(|e| ServiceError::ConfigurationError(format!("JSON serialization failed: {}", e)))
    }
    
    pub fn from_json(json: &str) -> Result<Self, ServiceError> {
        serde_json::from_str(json)
            .map_err(|e| ServiceError::ConfigurationError(format!("JSON deserialization failed: {}", e)))
    }
}

// 配置管理器
pub struct ConfigManager {
    config: SimpleConfig,
    config_file: Option<std::path::PathBuf>,
}

impl ConfigManager {
    pub fn new() -> Self {
        info!("Creating new ConfigManager");
        Self {
            config: SimpleConfig::new(),
            config_file: None,
        }
    }
    
    pub fn with_config(mut self, config: SimpleConfig) -> Self {
        self.config = config;
        self
    }
    
    pub fn load_from_file(&mut self, path: &std::path::Path) -> Result<(), ServiceError> {
        info!("Loading configuration from: {}", path.display());
        
        let content = std::fs::read_to_string(path)
            .map_err(|e| ServiceError::ConfigurationError(format!("Failed to read config file: {}", e)))?;
            
        self.config = SimpleConfig::from_json(&content)?;
        self.config.validate()?;
        self.config_file = Some(path.to_path_buf());
        
        info!("Configuration loaded successfully");
        Ok(())
    }
    
    pub fn save_to_file(&self, path: &std::path::Path) -> Result<(), ServiceError> {
        info!("Saving configuration to: {}", path.display());
        
        let json = self.config.to_json()?;
        std::fs::write(path, json)
            .map_err(|e| ServiceError::ConfigurationError(format!("Failed to write config file: {}", e)))?;
            
        info!("Configuration saved successfully");
        Ok(())
    }
    
    pub fn get_config(&self) -> &SimpleConfig {
        &self.config
    }
    
    pub fn get_config_mut(&mut self) -> &mut SimpleConfig {
        &mut self.config
    }
    
    pub fn reload(&mut self) -> Result<(), ServiceError> {
        if let Some(path) = &self.config_file {
            let path_clone = path.clone();
            self.load_from_file(&path_clone)
        } else {
            Err(ServiceError::ConfigurationError("No config file path set".to_string()))
        }
    }
}